// 状态管理工具
import React, { createContext, useContext, useReducer } from 'react';
import { $globalContextType, $globalActionType, $globalStateInterface } from '../common/type';

/** 创建Context并设置默认值 */
const GlobalContext = createContext<$globalContextType | undefined>(undefined);

/** 定义初始状态 */
const initialState: $globalStateInterface = {
  isLoading: false,
};

/**
 * @brief 创建 Reducer 函数
 * @param state:GlobalState 状态
 * @param action:GlobalAction 功能
 * @return 对应的变量值
 * @note 
 * @warning 
 */
const globalReducer = (state: $globalStateInterface, action: $globalActionType): $globalStateInterface => {
  switch (action.type) {
    case 'SET_LOADING':
      return { ...state, isLoading: action.payload };
  }
}

/**
 * @brief 创建 Provider 组件
 * @param children:React.ReactNode 应用的组件
 * @return 
 * @note 
 * @warning 
 */
export const GlobalProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(globalReducer, initialState);
  return (
    <GlobalContext.Provider value={{ state, dispatch }}>
      {children}
    </GlobalContext.Provider>
  );
}

/**
 * @brief 创建自定义 Hook
 * @param 
 * @return 全局数据
 * @note 
 * @warning 
 */
export const useGlobalContext = () => {
  const context = useContext(GlobalContext);
  if (context === undefined) {
    throw new Error('useGlobalContext必须在GlobalProvider内使用');
  }
  return context;
}

/**
 * @brief 获取全局数据
 * @param 
 * @return 全局数据
 * @note 使用方法：const { } = useGlobalState();
 * @warning 
 */
export const useGlobalState = () => {
  const { state } = useGlobalContext();
  return state;
}

/**
 * @brief 更改全局数据
 * @param 
 * @return 全局数据的更改函数
 * @note 使用方法：声明 const dispatch = useGlobalDispatch();
 *                执行 dispatch({ type: '', payload:  });
 * @warning 
 */
export const useGlobalDispatch = () => {
  const { dispatch } = useGlobalContext();
  return dispatch;
}